package HuaWei;

/**
 Java写死锁程序实例
 设计思想：
 1.建立两个资源标记Object对象 a 和 b
 2.设置两个线程A，B
 3.用A去锁住a,用B去锁住b，使a，b都被占有，
 4.这时再用A去锁b，表示A目前需要b资源，因b目前被B占有，此时A无法锁住b
 5.同理，用B去锁a，B也无法去锁住a，形成死锁，A,B陷于无限等待，形成死锁
 */
public class DeadLock {
    public static Object a = new Object();
    public static Object b = new Object();

    public static void main(String[] args){
        DeadLock d = new DeadLock();
        d.setDeadlock();
    }

    // 建立死锁
    private void setDeadlock() {
        Thread A = new Thread(new Runnable() {
            @Override
            public void run() {
                threadA();
            }
        });
        Thread B = new Thread(new Runnable() {
            @Override
            public void run() {
                threadB();
            }
        });
        A.start();
        B.start();
    }
    protected void threadA() {
        synchronized (DeadLock.a) {
            System.out.println("A keeps a");
            sleep();  // 留出时间让线程B去锁住b
            synchronized (DeadLock.b) {
                System.out.println("A got b");
                sleep();
            }
        }
    }

    private void threadB() {
        synchronized (DeadLock.b) {
            System.out.println("B keeps b");
            sleep();  // 留出时间让线程A去锁住a
            synchronized (DeadLock.a) {
                System.out.println("B got a");
                sleep();
            }

        }
    }

    // 让线程等待一段时间，以便使A,B都能先锁住一个资源
    private void sleep() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}


